<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { ElButton } from 'element-plus'

import { Table } from '@/components/Table'

import { sysDictRelsApi } from '@/api/dict'

import { useTable } from '@/hooks/web/useTableTest'
import { ref, reactive, unref } from 'vue'

import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
// import { zcLoanOrderListApi } from '@/api/cy/Loanapply'
import { dbLoanOrderDetailedListApi, dbLoanOrderDetailedexportApi } from '@/api/forms'
import { zcPastureListApi } from '@/api/fa/user'

const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const dictRelsData = ref() // 联动数据
const breedSubData: any = ref([]) // 品种的枚举
const searchRef = ref() // 搜索的标签

const defaultTime = ref<[Date, Date]>([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59)
])

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: dbLoanOrderDetailedListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { setSearchParams } = methods

// 选择畜别的时候触发，处理品种类容
const breedChange = (value) => {
  breedGetSub(value)
  const new_search = unref(searchRef)
  new_search.setData({ ...new_search.getData(), breed_sub: '' })
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

let crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 100,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_id',
    label: '组织',
    table: {
      show: false
    },
    search: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: zcPastureListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择组织（双击选择）',
        nameField: 'org_name',
        relNameField: 'org_name',
        valueField: 'org_id',
        relValueField: 'org_id',
        crudSchemas: [
          {
            field: 'org_name',
            label: '组织名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      },
      show: true
    },
    form: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: zcPastureListApi,
        response: {
          count: 'count',
          data: 'data'
        },
        title: '选择组织（双击选择）',
        nameField: 'org_name',
        relNameField: 'org_name',
        valueField: 'org_id',
        relValueField: 'org_id',
        crudSchemas: [
          {
            field: 'org_name',
            label: '组织名称',
            fixed: 'left',
            search: {
              show: true
            }
          }
        ]
      }
    }
  },
  {
    field: 'pasture_name',
    label: '牧场名称',
    width: 200,
    search: {
      show: false
    }
  },
  {
    field: 'bank_org_name',
    label: '贷款银行',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'loan_order_code',
    label: '贷款申报编号',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'asset_code',
    label: '资产编号(注射)',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'asset_code_2',
    label: '资产编号(项圈)',
    width: 200,
    search: {
      show: false
    }
  },
  {
    field: 'earcon_code',
    label: '耳标编码',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'breed',
    label: '畜别',
    width: 80,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.breed,
        onChange: breedChange
      },
      show: true
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    width: 120,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: breedSubData
      },
      show: true
    }
  },
  {
    field: 'loan_no',
    label: '单款单号',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'amount',
    label: '贷款金额',
    width: 200,
    search: {
      show: false
    }
  },
  // {
  //   field: 'code',
  //   label: '贷款编号',
  //   width: 150,
  //   search: {
  //     show: true
  //   }
  // },
  {
    field: 'loan_data',
    component: 'DatePicker',
    label: '贷款日期',
    width: 170,
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        defaultTime: defaultTime
      }
    }
  },
  {
    field: 'loan_year',
    label: '贷款年限',
    width: 200,
    search: {
      show: true
    }
  },
  // {
  //   field: 'end_date',
  //   component: 'DatePicker',
  //   label: '结束时间',
  //   width: 170,
  //   componentProps: {
  //     valueFormat: 'YYYY-MM-DD'
  //   }
  // },
  {
    field: 'loan_state',
    label: '状态',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('loan_order_state', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.loan_order_state
      },
      show: true
    }
  },
  //   {
  //     field: 'code',
  //     label: '贷款申报单编号',
  //     width: 150,
  //     search: {
  //       show: true
  //     }
  //   },
  //   {
  //     field: 'state',
  //     label: '状态',
  //     width: 150,
  //     formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
  //       return getDictLabel('loan_order_state', cellValue)
  //     },
  //     table: {
  //       show: true
  //     }
  //   },
  //   {
  //     field: 'loan_no',
  //     label: '贷款单号',
  //     width: 100,
  //     search: {
  //       show: true
  //     }
  //   },
  //   {
  //     field: 'number',
  //     label: '牲畜数量',
  //     width: 150,
  //     search: {
  //       show: false
  //     }
  //   },
  {
    field: 'note',
    label: '备注',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 170,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        defaultTime: defaultTime
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const init = async () => {
  await getDictRels()
}
init()

const exportClick = async () => {
  dialogTableVisible.value = true
  Load.value = true
  let aaa: any = tableObject.paramsObj.params
  console.log(aaa, tableObject.count)

  let res: any = await dbLoanOrderDetailedListApi({
    ...aaa
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    Load.value = false

    FormsNumber.value = Math.ceil(res.count / 10000)
  }
}

const FormsNumber = ref(0)
const dialogTableVisible = ref(false)
const Load = ref(false)
const Export = async (index) => {
  let aaa: any = tableObject.paramsObj.params
  console.log(aaa, index)
  let { data }: any = await dbLoanOrderDetailedexportApi({
    request: {
      ...aaa,
      pageNo: index,
      pageSize: '10000'
    },
    layout_data: {
      file_name: '贷款申报单资产明细列表',
      column_cell_start: 'A2',
      column_data: [
        {
          title: '序号',
          width: 5,
          cell_type: 'key'
        },
        {
          title: '牧场名称',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'pasture_name'
        },
        {
          title: '贷款银行',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'bank_org_name'
        },
        {
          title: '贷款申报单号',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'loan_order_code'
        },
        {
          title: '资产编号（注射）',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'asset_code'
        },
        {
          title: '资产编号（项圈）',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'asset_code_2'
        },
        {
          title: '耳标编号',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'earcon_code'
        },
        {
          title: '贷款单号',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'loan_no'
        },
        {
          title: '贷款金额',
          width: 20,
          cell_type: 'number',
          decimal: 2,
          give_type: 'variable',
          give_value: 'amount'
        },
        {
          title: '贷款日期',
          width: 15,
          cell_type: 'date',
          give_type: 'variable',
          give_value: 'loan_data'
        },
        {
          title: '贷款年限',
          width: 10,
          cell_type: 'number',
          give_type: 'variable',
          give_value: 'loan_year'
        },
        {
          title: '状态',
          width: 8,
          cell_type: 'dict',
          dict_type: 'loan_state',
          give_type: 'variable',
          give_value: 'state'
        },
        {
          title: '备注',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'note'
        },
        {
          title: '创建人',
          width: 20,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'create_user_name'
        },
        {
          title: '创建时间',
          width: 20,
          cell_type: 'datetime',
          give_type: 'variable',
          give_value: 'create_time'
        }
      ],
      custom: [
        {
          cell_type: 'string',
          cell: 'A1:O1',
          give_type: 'format',
          give_value: '贷款申报单资产明细列表',
          horizontal: 'center',
          border: true,
          size: '16'
        }
      ]
    }
  })
    .catch(() => {})
    .finally(() => {
      // saveLoading.value = false
    })
  if (data) {
    Load.value = false
    window.open(data.url)

    console.log(data, Math.ceil(data.count / 10000))
    // FormsNumber.value = Math.ceil(data.count / 10000)
  }
}
</script>

<template>
  <ContentWrap>
    <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px w-[100%] flex justify-end" v-show="tableObject.paramsObj.params">
      <ElButton type="primary" @click="exportClick()"> 导出EXCEL </ElButton>
    </div>

    <Table
      v-show="tableObject.paramsObj.params"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :loading="tableObject.loading"
      :data="tableObject.tableList"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    />
  </ContentWrap>

  <el-dialog v-model="dialogTableVisible" title="贷款主档导出详情">
    <el-table v-loading="Load" style="width: 100%" v-show="Load" />
    <div style="margin: 20px" v-for="(item, index) in FormsNumber" :key="index">
      <span style="margin: 20px">贷款主档 - {{ item }}</span>
      <ElButton type="primary" @click="Export(item)">导出</ElButton>
    </div>
  </el-dialog>
</template>
